package com.yotoodesign.core.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.protocol.HTTP;

import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.yotoodesign.dianba.util.Constant;

/**
 * 异步访问远程服务，获取数据
 * 第一个参数 就是要访问的服务url地址 
 * 第二个参数是 下载的进度 
 * 第三个参数就是异步任务执行完毕后的返回值
 * 
 * @author Administrator
 * 
 */


public class LoadDataAsynTask extends AsyncTask<String, Void, String> {
	LoadDataAsynTaskCallback loadDataAsynTaskCallback;
	
	//功能代码
	public static int funcode = 1;

	public LoadDataAsynTask(LoadDataAsynTaskCallback loadDataAsynTaskCallback) {
		this.loadDataAsynTaskCallback = loadDataAsynTaskCallback;
	}

	public interface LoadDataAsynTaskCallback {
		
		public boolean beforeLoadData();

		public void afterLoadData(String data);
	}

	/**
	 * 当异步任务执行之前调用
	 */
	@Override
	protected void onPreExecute() {
		// 初始化的操作具体怎么去实现, LoadDataAsynTask 不知道
		// 需要让调用这个 LoadDataAsynTask 的人 去实现
		boolean exists = loadDataAsynTaskCallback.beforeLoadData();
		super.onPreExecute();
		
		//如果本地缓存已经有数据，就不要去获取
		if(exists){
			this.cancel(true);
		}
	}

	/**
	 * 异步任务执行之后调用
	 */
	@Override
	protected void onPostExecute(String result) {
		loadDataAsynTaskCallback.afterLoadData(result);
		super.onPostExecute(result);
	}

	/**
	 * 后台子线程运行的异步任务 String... params 可变长度的参数
	 */
	@Override
	protected String doInBackground(String... params) {
		byte[] data = new byte[1024];
		int len = 0;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		String result = "";
		HttpURLConnection conn = null;
		try {
			String serviceUrl = params[0];//url地址
			String ps = params[1];//url参数
			Log.i(Constant.DIANBA,"serviceUrl>>>>"+serviceUrl);
			Log.i(Constant.DIANBA,"param>>>>"+ps);
			//如果路径为空，就不要去尝试获取数据
			if(serviceUrl==null && TextUtils.isEmpty(serviceUrl)){
				return null;
			}
			
			URL url = new URL(serviceUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(6*1000);
			conn.setReadTimeout(6*1000);
			conn.setRequestMethod("POST");
			//需要输入入参
			if(ps!=null && !ps.equals("")){
				conn.setDoOutput(true);
				conn.getOutputStream().write(ps.getBytes());
			}
			
			InputStream is = conn.getInputStream();
			switch(funcode){
			case 0:
				//返回结果数据获取
				while ((len = is.read(data)) > -1) {
					outStream.write(data, 0, len);
				}
				outStream.flush();
				result = outStream.toString(HTTP.UTF_8);
				break;
			case 1:
				break;
			}
			
			Log.i(Constant.DIANBA,"result>>>>"+conn.getResponseCode()+","+result);
			if(conn!=null){
				conn.disconnect();
			}
			
			return result;
		} catch (Exception e) {
			if(conn!=null){
				conn.disconnect();
			}
			e.printStackTrace();
			return result;
		} 

	}
	

	//访问服务获取数据
	public static void loadDataFromUrl(final String url,String params,final String cacheDir){
		if(url==null || url.equals("")){
			return;
		}
		
		new LoadDataAsynTask(new LoadDataAsynTaskCallback() {
			OutputStream out;
			ByteArrayOutputStream baos;
			//获取SD卡缓存目录路径
			final String dir = Environment.getExternalStorageDirectory()
					.getPath() + "/" + cacheDir+"/";
			
			@Override
			public boolean beforeLoadData() {
				return false;
			}

			@Override
			public void afterLoadData(String result) {
				
				//如果有SD卡，则保存数据到SD卡上缓存目录
				if (Environment.getExternalStorageState()
						.equals(Environment.MEDIA_MOUNTED) && result!=null) {// sd卡存在
					File fileDir = new File(dir);
					if (!fileDir.exists()) {
						fileDir.mkdirs();
					}
					/**
					try {
						File file = new File(fileDir, imgName);
						file.createNewFile();
						out = new FileOutputStream(file);
						baos = new ByteArrayOutputStream();
						out.write(baos.toByteArray());
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							if (baos != null && out != null) {
								baos.close();
								out.close();
							}

						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					*/
				}
			}
		}).execute(url,params);
	}
	
	//解析查询数据
	public static ArrayList parseArrayList(String data){
		ArrayList result = new ArrayList();
		String[] ary1 = data.split("##");
		if(ary1!=null && ary1.length>0){
			for(int i = 0;i<ary1.length;i++){
				String[]ary2 = ary1[i].split(",");
				if(ary2!=null && ary2.length>0){
					for(int j = 0;j<ary2.length;j++){
						//TODO:
					}
				}
			}
		}
		return result;
	}

}
